package com.insmess.speech.sdk.template;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.insmess.speech.sdk.dto.AsrRequestDto;
import com.insmess.speech.sdk.dto.AsrResponseDto;
import com.insmess.speech.sdk.util.FileBase64Utils;
import lombok.SneakyThrows;

public class InsmessAsrTemplate {

    private String url;

    public InsmessAsrTemplate(String url) {
        this.url = url;
    }

    /**
     * 根据文件路径进行语音识别
     * @param filePath
     * @return
     */
    @SneakyThrows
    public AsrResponseDto asrRequest(String filePath) {
        HttpRequest http = HttpUtil.createPost(url);
        //构造请求体
        AsrRequestDto asrRequestDto = new AsrRequestDto();
        String base64 = FileBase64Utils.convertFileToBase64(filePath);
        asrRequestDto.setAudio(base64);
        asrRequestDto.setAudioFormat("wav");
        asrRequestDto.setSampleRate(16000);
        asrRequestDto.setLang("zh_cn");
        asrRequestDto.setPunc(1);
        return getAsrResponseDto(http, asrRequestDto);
    }



    /**
     * 根据文件路径以及自定义的asrRequestDto的信息进行语音识别
     * @param filePath
     * @param asrRequestDto
     * @return
     */
    @SneakyThrows
    public AsrResponseDto asrRequest(String filePath, AsrRequestDto asrRequestDto) {
        HttpRequest http = HttpUtil.createPost(url);
        //转base64封装
        String base64 = FileBase64Utils.convertFileToBase64(filePath);
        asrRequestDto.setAudio(base64);
        //构造请求体
        return getAsrResponseDto(http, asrRequestDto);
    }

    /**
     * 根据AsrRequestDto的内容进行语音识别
     * @param asrRequestDto
     * @return
     */
    @SneakyThrows
    public AsrResponseDto asrRequest(AsrRequestDto asrRequestDto) {
        HttpRequest http = HttpUtil.createPost(url);
        //构造请求体
        return getAsrResponseDto(http, asrRequestDto);
    }

    /**
     * HTTP发送http请求并将结果转换
     * @param http
     * @param asrRequestDto
     * @return
     * @throws JsonProcessingException
     */
    private AsrResponseDto getAsrResponseDto(HttpRequest http, AsrRequestDto asrRequestDto) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(asrRequestDto);
        HttpResponse resp = http.body(json).execute();
        String body = resp.body();
        AsrResponseDto asrResponseDto = objectMapper.readValue(body, AsrResponseDto.class);
        return asrResponseDto;
    }
}
